home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!usenet
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: [Q] Recursive mechanism
- Date: Mon, 15 Apr 1996 13:01:20 -0400
- Organization: Datalytics, Inc
- Message-ID: <317280E0.1340@datalytics.com>
- References: <4khu5s$oop@dfw-ixnews1.ix.netcom.com>
- NNTP-Posting-Host: 204.62.224.71
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- stefmit@ix.netcom.com wrote:
- >
- > Could anybody explain the mechanism behind the following (broken) code:
- > in a linked list:
- > void List<type> :: reverse (Node<type> *p) const
- > { while ( p!= 0)
- > reverse (p -> next);
- > cout << p -> data; }
- > that is, replacing if with while to get an infinite loop?
- > How does it differ in the way of processing from the correct usage of if?
- > NOTE: the first call is made with reverse(first_element_pointer)
- > Thanks.
-
- I'm not quite sure what your question is, but I think you're
- asking why while makes this an infinite loop and why if
- wouldn't. If p is non-zero, the loop is, simply:
-
- while (p);
-
- Since the body of the loop doesn't change the value of p, the
- condition never changes, resulting in an infinite loop.
- Obviously, using if only checks the condition once, regardless
- of the outcome, so it isn't an infinite loop. Now, at this
- point, I have to assume there is more to this function than you
- have posted here. Otherwise, "reverse" does nothing but print
- the data of each node from p to the end of the list.
-
- Clearly, this code:
-
- void List<type>::reverse(Node<type> *p) const
- {
- if (p)
- {
- reverse(p->next);
- cout << p->data;
- }
- }
-
- implements the desired functionality of reverse as presently
- given.
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc. | stew@datalytics.com
-